//获取应用实例
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    scanCodeNumber: "",
    checkedbox:false
  },
  onLoad: function(options) {
    // Do some initialize when page load.
  },
  onReady: function() {
    // Do something when page ready.
  },
  onShow: function() {
    // Do something when page show.
  },
  onHide: function() {
    // Do something when page hide.
  },
  onUnload: function() {
    // Do something when page close.
  },
  onPullDownRefresh: function() {
    // Do something when pull down.
  },
  onReachBottom: function() {
    // Do something when page reach bottom.
  },
  onShareAppMessage: function() {
    // return custom share data when user share.
  },
  onPageScroll: function() {
    // Do something when page scroll
  },
  onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
  },
  // Event handler.
  scanCode: function() {
    if (!this.data.checkedbox) {
      wx.showToast({
        icon: 'none',
        title: "请阅读用户协议",
      })
      return;
    }
    const _this = this;
    // 只允许从相机扫码
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        let code = res.result.substring(2,12)
        _this.setData({
          scanCodeNumber: code
        })
        _this.login();
      }
    })
  },
  login() {
    if (!this.data.checkedbox){
      wx.showToast({
        icon: 'none',
        title: "请阅读用户协议",
      })
      return;
    }
    let param = {
      "patientId": this.data.scanCodeNumber
    };
    api.POST({
      url: 'login.action',
      params: param,
      success: function(res) {
        let success = res.data.success;
        if (success == "true") {
          wx.showToast({
            icon: 'none',
            title: "登录成功",
          })
          let user = res.data.data[0]; //replace(/\s+/g, '')
          user.bh = user.bh.replace(/\s+/g, '');
          wx.setStorage({
            key: 'user',
            data: user,
            success: function(res) {
              wx.switchTab({
                url: '../index2/index'
              })
            }
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
          })
        }
      },
      fail: function() {
        wx.showToast({
          icon: 'none',
          title: '请求失败',
        })
      },
    })

  },
  inputNumber(e) {
    this.setData({
      scanCodeNumber: e.detail.value
    })
  },
  checkboxChange(e) {
    console.log(e.detail.value)
    if (e.detail.value == "true") {
      this.setData({
        checkedbox: true
      })
    }else{
      this.setData({
        checkedbox: false
      })
    }

  }
})